package log

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
	"websocket_apn/log/transport"
)

const (
	//日志级别的key
	LOG_LEVEL_KEY = "log-level-key"
)

var setLogLevelOnce sync.Once

//远程设置日志级别
func removeSetLogLevel(logLevel int) error {
	tran := transport.NewDefaultTransport()
	url := filepath.Join(os.TempDir(), os.Args[0])
	client, err := tran.Dial(url, transport.WithTimeout(time.Second*10))
	if err != nil {
		return err
	}
	msg := transport.NewMessage()
	msg.Header[LOG_LEVEL_KEY] = fmt.Sprint(logLevel)
	defer client.Close()
	if err := client.Send(msg); err != nil {
		return err
	}
	return nil
}

func recvRemoveLogLevelInfo() error {
	var err error
	setLogLevelOnce.Do(func() {
		tran := transport.NewDefaultTransport()
		url := filepath.Join(os.TempDir(), os.Args[0])
		lister, err := tran.Listen(url)
		if err != nil {
			err = err
			return
		}
		defer lister.Close()
		lister.Accept(func(socket transport.Socket) {
			defer socket.Close()
			msg := transport.NewMessage()
			if err := socket.Recv(msg); err != nil {
				return
			}
			if strLevel, ok := msg.Header[LOG_LEVEL_KEY]; ok {
				iLevel, _ := strconv.Atoi(strLevel)
				logLevel = level(iLevel)
			}
			return
		})
	})
	return err
}

func lineInfo(dept int) (string, string) {
	_, file, line, ok := runtime.Caller(dept)
	if !ok {
		file = "???"
		line = 1
	} else {
		slash := strings.LastIndex(file, "/")
		if slash >= 0 {
			file = file[slash+1:]
		}
	}
	return file, fmt.Sprint(line)
}
